<template>
    <div class="box">
        <div class="top">
            <div class="top_one">
                <div class="back" @click="$router.back()">
                    <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M25 5L10 20L25 35" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </div>
                <div class="mode-btn" @click="handleSave">
                    保存
                </div>
            </div>
            <div class="top_two">
                <div class="expense" 
                     :class="{ 'zcsr_active': currentType === 'expense' }"
                     @click="switchType('expense')">
                     支出
                </div>
                <div class="income" 
                     :class="{ 'zcsr_active': currentType === 'income' }"
                     @click="switchType('income')">
                     收入
                </div>
            </div>
        </div>
        <div class="cont">
            <div class="cont_sum">
                <div class="cy">
                    常用类别
                </div>
                <div class="sum">
                    <div class="sum_item" 
                         v-for="category in frequentCategories" 
                         :key="category._id"
                         :class="{ 'selected': selectedCategory?._id === category._id }"
                         @click="selectCategory(category)">
                        <svgIcon :iconName="category.icon" font-size="70px"></svgIcon>
                        <p>{{ category.name }}</p>
                    </div>
                </div>
            </div>
            <div class="cont_all">
                <div class="qb">
                    全部类别
                </div>
                <div class="all">
                    <div class="all_item" 
                         v-for="category in allCategories" 
                         :key="category._id"
                         :class="{ 'selected': selectedCategory?._id === category._id }"
                         @click="selectCategory(category)">
                        <svgIcon :iconName="category.icon" font-size="70px"></svgIcon>
                        <p>{{ category.name }}</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="price">
                <div class="time">{{ currentTime }}</div>
                <div class="num">{{ inputValue }}</div>
            </div>
            <div class="keyboard">
                <div class="keyboard-row" v-for="(row, rowIndex) in keyboardLayout" :key="rowIndex">
                    <div class="key" 
                         v-for="key in row" 
                         :key="key"
                         :class="{ 'key-special': ['+', '-', '.', '删除', '保存'].includes(key) }"
                         @click="handleKeyPress(key)">
                        {{ key }}
                    </div>
                </div>
            </div>
        </div>
        <MessageBox ref="messageBox" />
    </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import MessageBox from '../components/MessageBox.vue'
import request from '../utils/request'

const router = useRouter();
const route = useRoute();
const messageBox = ref(null);
const currentType = ref('expense');
const categories = ref([]);
const frequentCategories = ref([]);
const allCategories = ref([]);
const inputValue = ref('0');
const currentTime = ref('');
const selectedCategory = ref(null);
const isEdit = ref(false);

// 键盘布局
const keyboardLayout = [
    ['1', '2', '3', '+'],
    ['4', '5', '6', '-'],
    ['7', '8', '9', '.'],
    ['删除', '0', '保存']
];

// 检查是否是编辑模式
onMounted(() => {
    const query = route.query;
    console.log('路由参数:', query);
    console.log('当前路由:', route.fullPath);
    
    if (query.isEdit) {
        console.log('进入编辑模式');
        isEdit.value = true;
        // 设置当前类型
        currentType.value = query.type || 'expense';
        console.log('当前类型:', currentType.value);
        // 设置金额
        inputValue.value = query.amount?.toString() || '0';
        console.log('当前金额:', inputValue.value);
        // 设置时间（编辑模式下显示原始时间）
        currentTime.value = query.time ? formatTime(new Date(query.time)) : formatTime();
        console.log('当前时间:', currentTime.value);
        
        // 获取类别数据并选择对应类别
        fetchCategories(currentType.value).then(() => {
            console.log('获取到的类别列表:', categories.value);
            // 使用类别名称查找类别
            const category = categories.value.find(cat => cat.name === query.category);
            console.log('查找的类别名称:', query.category);
            console.log('找到的类别:', category);
            
            if (category) {
                selectedCategory.value = category;
                console.log('已选择类别:', selectedCategory.value);
            } else {
                console.error('未找到对应的类别:', query.category);
                messageBox.value.show('未找到对应的类别', null);
            }
        });
    } else {
        console.log('进入新增模式');
        fetchCategories(currentType.value); 
        updateTime();
    }
    // 每分钟更新一次时间（仅在非编辑模式下）
    if (!isEdit.value) {
        setInterval(updateTime, 60000);
    }
});

// 修改格式化时间函数以接受日期参数
const formatTime = (date = new Date()) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}.${month}.${day} ${hours}:${minutes}`;
};

// 更新时间
const updateTime = () => {
    currentTime.value = formatTime();
};

// 处理按键点击
const handleKeyPress = (key) => {
    switch(key) {
        case '删除':
            handleDelete();
            break;
        case '保存':
            handleSave();
            break;
        case '.':
            handleDecimalPoint();
            break;
        case '+':
        case '-':
            // TODO: 实现加减逻辑
            console.log('操作符:', key);
            break;
        default:
            handleNumber(key);
    }
};

// 处理数字输入
const handleNumber = (key) => {
    // 如果当前是0，直接替换
    if (inputValue.value === '0') {
        inputValue.value = key;
        return;
    }

    // 如果包含小数点
    if (inputValue.value.includes('.')) {
        const parts = inputValue.value.split('.');
        // 如果小数部分不足两位
        if (parts[1].length < 2) {
            inputValue.value = inputValue.value + key;
        }
    } else {
        // 输入整数部分
        inputValue.value = inputValue.value + key;
    }
};

// 处理小数点
const handleDecimalPoint = () => {
    // 如果已经包含小数点，不做任何操作
    if (inputValue.value.includes('.')) {
        return;
    }
    // 添加小数点
    inputValue.value = inputValue.value + '.';
};

// 处理删除
const handleDelete = () => {
    // 如果长度为1，重置为0
    if (inputValue.value.length === 1) {
        inputValue.value = '0';
        return;
    }
    // 删除最后一个字符
    inputValue.value = inputValue.value.slice(0, -1);
};

// 修改保存函数以处理编辑模式
const handleSave = async () => {
    // 验证金额和类别
    if (inputValue.value === '0' || !selectedCategory.value) {
        messageBox.value.show('请选择类别并输入金额', null);
        return;
    }

    try {
        // 处理金额，确保两位小数
        let amount = parseFloat(inputValue.value);
        if (isNaN(amount)) {
            messageBox.value.show('金额格式错误', null);
            return;
        }
        // 格式化为两位小数
        amount = Number(amount.toFixed(2));

        // 获取现有类别数据
        const response = await request.get('/api/category/categories', { params: { type: currentType.value } }, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const categories = response.data;
        
        console.log('当前路由参数:', route.query);
        console.log('获取到的类别数据:', categories);
        
        // 找到选中的类别
        const selectedCategoryData = categories.find(cat => cat.name === selectedCategory.value.name);
        if (!selectedCategoryData) {
            throw new Error('未找到选中的类别');
        }

        console.log('选中的类别:', selectedCategoryData);
        console.log('要修改的记录ID:', route.query._id);

        if (isEdit.value) {
            // 编辑模式
            const originalCategoryName = route.query.category;
            const originalCategory = categories.find(cat => cat.name === originalCategoryName);
            
            if (!originalCategory) {
                throw new Error('未找到原始类别');
            }

            // 检查类别是否改变
            const isCategoryChanged = originalCategoryName !== selectedCategoryData.name;
            console.log('类别是否改变:', isCategoryChanged);

            if (!isCategoryChanged) {
                // 类别未改变，只更新金额
                console.log('类别未改变，更新金额');
                const updateData = {
                    ...originalCategory,
                    data: originalCategory.data.map(item => {
                        if (item._id === route.query._id) {
                            return {
                                ...item,
                                value: amount
                            };
                        }
                        return item;
                    })
                };

                const updateResponse = await request.put(`/api/category/categories/${originalCategory._id}`, updateData, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                console.log('更新金额响应:', updateResponse);
            } else {
                // 类别已改变，需要移动记录
                console.log('类别已改变，移动记录');
                
                // 1. 从原类别中删除记录
                const originalRecord = originalCategory.data.find(item => item._id === route.query._id);
                if (!originalRecord) {
                    throw new Error('未找到要编辑的记录');
                }

                const originalUpdateData = {
                    ...originalCategory,
                    data: originalCategory.data.filter(item => item._id !== route.query._id)
                };
                await request.put(`/api/category/categories/${originalCategory._id}`, originalUpdateData, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                console.log('从原类别删除记录成功');

                // 2. 添加到新类别
                const newUpdateData = {
                    ...selectedCategoryData,
                    data: [...(selectedCategoryData.data || [])]
                };
                newUpdateData.data.push({
                    _id: route.query._id,
                    value: amount,
                    category: selectedCategoryData.name,
                    type: currentType.value,
                    icon: selectedCategoryData.icon,
                    time: originalRecord.time // 保持原始时间
                });

                const updateResponse = await request.put(`/api/category/categories/${selectedCategoryData._id}`, newUpdateData, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                console.log('添加到新类别响应:', updateResponse);
            }
        } else {
            // 新增模式：添加新记录
            const updateData = {
                ...selectedCategoryData,
                data: [...(selectedCategoryData.data || [])]
            };
            updateData.data.push({
                value: amount,
                category: selectedCategoryData.name,
                type: currentType.value,
                icon: selectedCategoryData.icon,
                time: new Date().toISOString()
            });

            const updateResponse = await request.put(`/api/category/categories/${selectedCategoryData._id}`, updateData, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            console.log('新增记录响应:', updateResponse);
        }

        // 保存成功后跳转到首页
        router.push('/home');
    } catch (error) {
        console.error('保存失败:', error);
        console.error('错误详情:', {
            message: error.message,
            response: error.response?.data,
            status: error.response?.status
        });
        messageBox.value.show(error.message || '保存失败，请重试', null);
    }
};

// 获取类别数据
const fetchCategories = async (type) => {
    try {
        const response = await request.get('/api/category/categories', { params: { type: type } }, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const data = response.data;
        // 确保只显示当前类型的类别
        categories.value = data.filter(category => category.type === type);
        console.log('获取到的类别数据:', categories.value);
        
        // 处理常用类别
        const categoriesWithDataLength = categories.value.map(category => {
            // 计算嵌套data数组的长度
            const nestedDataLength = category.data.length
            
            return {
                ...category,
                dataLength: nestedDataLength
            };
        });
        
        // 按嵌套data数组长度排序并获取前4个
        frequentCategories.value = categoriesWithDataLength
            .sort((a, b) => b.dataLength - a.dataLength)
            .slice(0, 5);
            
        // 所有类别
        allCategories.value = categories.value;
        
        console.log('常用类别:', frequentCategories.value);
    } catch (error) {
        console.error('获取类别数据失败:', error);
    }
};

// 切换类别类型
const switchType = (type) => {
    currentType.value = type;
    fetchCategories(type);
};

// 选择类别
const selectCategory = (category) => {
    selectedCategory.value = category;
};
</script>
<style lang="less" scoped>
.box {
    width: 100%;
    height: 100vh;
    position: relative;
    overflow: hidden;
    
    .top {
        width: 100%;
        height: 190px;
        background-color: #fb8fae;
        color: #fff;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 100;
        .top_one {
            width: 100%;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 30px;
            .back {
                width: 120px;
                height: 100%;
                line-height: 50px;
                text-align: center;
                display: flex;
                align-items: center;
                svg {
                    width: 40px;
                    height: 40px;
                }
            }
            .mode-btn {
                width: 120px;
                font-size: 28px;
                text-align: center;
                height: 100%;
                line-height: 100px;
                cursor: pointer;
                transition: all 0.3s ease;
                
                &:active {
                    opacity: 0.7;
                }
            }
        }
        .top_two {
            width: 100%;
            height: 70px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 32px;
            .expense {
                width: 210px;
                height: 60px;
                border-radius: 10px 0 0 10px;
                border: 1px solid #fff;
                text-align: center;
                line-height: 60px;
            }
            .income {
                width: 210px;
                height: 60px;
                border-radius: 0 10px 10px 0;
                border: 1px solid #fff;
                text-align: center;
                line-height: 60px;
            }
            .zcsr_active {
                background-color: #fff;
                color: #fb8fae;
            }

        }
    }
    .cont {
        margin-top: 190px;
        width: 100%;
        .cont_sum {
            width: 100%;
            background-color: #fbfbf1;
            .cy {
                background-color: #f5f5f5;
                color: gray;
                font-size: 24px;
                height: 40px;
                padding:0 30px;
            }
            .sum {
                padding-left: 30px;
                height: 175px;
                width: 100%;
                display: flex;
                align-items: center;
                overflow: hidden;
                .sum_item {
                    margin: 30px 20px 0 0;
                    width: 120px;
                    height: 120px;
                    text-align: center;
                    border-radius: 20px;
                    transition: all 0.3s ease;
                    cursor: pointer;
                    
                    &.selected {
                        background-color: rgba(251, 143, 174, 0.3);
                    }
                    
                    p {
                        color: #000;
                        font-size: 28px;
                    }
                }
            }
        }
        .cont_all {
            width: 100%;
            background-color: #fbfbf1;
            .qb {
                background-color: #f5f5f5;
                color: gray;
                font-size: 24px;
                height: 40px;
                padding:0 30px;
            }
            .all {
                padding-left: 30px;
                min-height: 620px;
                width: 100%;
                display: flex;
                flex-wrap: wrap;
                align-content: flex-start;
                .all_item {
                    margin: 30px 20px 0 0;
                    width: 120px;
                    height: 120px;
                    text-align: center;
                    border-radius: 20px;
                    transition: all 0.3s ease;
                    cursor: pointer;
                    
                    &.selected {
                        background-color: rgba(251, 143, 174, 0.3);
                    }
                    
                    p {
                        color: #000;
                        font-size: 28px;
                    }
                }
            }
        }
    }
    .bottom {
        width: 100%;
        height: 640px;
        position: fixed;
        bottom: 0;
        z-index: 100;
        background-color: #f5f5f5;
        .price {
            width: 100%;
            height: 100px;
            padding: 0 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .time {
                width: 280px;
                background-color: #ffebf2;
                color: #fb8fae;
                border: 1px solid #fb8fae;
                text-align: center;
                font-size: 24px;
                height: 50px;
                line-height: 50px;
                border-radius: 30px;
            }
            .num {
                color: #fb8fae;
                font-size: 50px;
            }
        }
        .keyboard {
            width: 100%;
            height: 540px;
            display: flex;
            flex-direction: column;
            padding: 20px;
            box-sizing: border-box;
            
            .keyboard-row {
                display: flex;
                justify-content: space-between;
                margin-bottom: 20px;
                flex: 1;
                
                .key {
                    flex: 1;
                    margin: 0 10px;
                    background-color: #fff;
                    border-radius: 20px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 36px;
                    color: #333;
                    cursor: pointer;
                    user-select: none;
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                    
                    &:active {
                        background-color: #eee;
                    }
                    
                    &.key-special {
                        background-color: #fb8fae;
                        color: #fff;
                        
                        &:active {
                            background-color: darken(#fb8fae, 10%);
                        }
                    }
                }
            }
        }
    }
}
</style>